//
//  XMLParse.mm
//  Meal Wheel
//
//  Created by Justin Dell on 7/4/08.
//  Copyright 2008 . All rights reserved.
//

#import "XMLParse.h"
#import <iostream>
#import <fstream>

bool haveFood = false;
bool haveType = false;

@implementation XMLParse

-(void)parseXML:(NSString *)file {
    BOOL success;
    NSURL *xmlURL = [NSURL fileURLWithPath:file];
    if (addressParser) 
        [addressParser release];
    addressParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
    [addressParser setDelegate:self];
    [addressParser setShouldResolveExternalEntities:YES];
    success = [addressParser parse];
    [addressParser release];
}

-(FoodTree *)getFoodTree {
    return foodTree;
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
 
    if ( [elementName isEqualToString:@"Foodlist"]) {
        if (!foodTree) {
            foodTree = new FoodTree();
            numFoods = 0;
        }
        return;
    }
 
    if ( [elementName isEqualToString:@"Food"] ) {
        numFoods++;
        return;
    }
 
    if ( [elementName isEqualToString:@"Name"] ) {
        haveFood = true;
        return;
    }
    
    if ( [elementName isEqualToString:@"Type"] ) {
        haveType = true;
        return;
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)theString {

    // Add the foods name to the tree when a food is reached
    if (haveFood) {
        foodTree->addFood([theString UTF8String]);
        haveFood = false;
        return;
    }

    // Add this type to the current food being parsed
    if (haveType) {
        foodTree->addTypeToFood([theString UTF8String]);
        haveType = false;
        return;
    }
}

-(void)writeXML:(string)path {
    foodTree->writeXML(path.c_str());
}

@end
